'''
Created on Apr 21, 2011

@author: david
'''
from UI import *
from model.model import Profile

from google.appengine.ext import webapp
from google.appengine.ext import db

class NewProfile(webapp.RequestHandler):
    
    def get(self):
        "Output form"
        
        # get user auth
        
        self.response.out.write(NEW_EMAIL_PG % self.list())
        
    def list(self):
        "retrieve and list emails from db"
        
        profiles = db.GqlQuery("Select * from Profile order by tmstmp")
        
        html = "<table>"
        cnt = 0
        cols = 3
        s = ''
        for profile in profiles:
            f = cnt % cols
            
            # determine col layout
            if not f:
                s = "%s<tr><td>%s</td>"
            elif f == 1:
                s = "%s<td>%s</td>"
            else:
                s = "%s<td>%s</td></tr>"
                
            # add to HTML    
            html = s % (html,profile.address)
            
            # bump col counter
            cnt += 1
              
        return "%s</table>" %  html

class  AddProfile(webapp.RequestHandler):       
    
    def post(self):
        "add email to datastorage"
        # check for duplicate
        em = self.request.get('address')
        print "EM Value: "+ em
        results = db.GqlQuery("select * from Profile where address = '%s'" % em).fetch(1)
        if not len(results):
            ins = Profile(address = em)
            ins.put()
        
        self.redirect("/new")

class ListUsers(webapp.RequestHandler):
    
    def get(self):
        self.response.out.write(INV_PG % self.list())
        
    def list(self):
        profiles = db.GqlQuery("Select * from Profile order by tmstmp")
        
        html = "<table><tr><th>#</th><th>Email</th><th>Submitter</th><th>Date</th></tr>"
        cnt = 0
        for profile in profiles:
            cnt += 1
            html = "%s<tr><td>%s</td><td>%s<td>%s</td><td>%s</td></tr>" % (html,cnt,profile.address,profile.uid,profile.tmstmp)
            
        return "%s</table>" %  html
